package cn.yunzhisheng.vui.assistant.tv;

import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.View;

public class VuiHandle {

    protected Context mContext;

    protected Dialog mDialog;

    protected View mRootView;

    public VuiHandle(Context ctx, View view) {
        mContext = ctx;
        mRootView = view;
    }

    public VuiHandle(Dialog dialog) {
        this(dialog.getContext(), dialog.getWindow().getDecorView());
        mDialog = dialog;
        if (dialog.isShowing()) {
            resume();
        }
    }

    public void resume() {
        registerReceiver();
    }

    public void pause() {
        unregisterReceiver();
    }

    protected void registerReceiver() {

        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction(WindowService.MSG_VIRTUAL_KEY_BACK);
            filter.addAction(WindowService.MSG_VIRTUAL_KEY_CENTER);
            filter.addAction(WindowService.MSG_VIRTUAL_KEY_LEFT);
            filter.addAction(WindowService.MSG_VIRTUAL_KEY_RIGHT);
            filter.addAction(WindowService.MSG_VIRTUAL_KEY_UP);
            filter.addAction(WindowService.MSG_VIRTUAL_KEY_DOWN);
            filter.addAction(WindowService.PROTOCAL_CUSTOMER_DATA);
            filter.addCategory(mContext.getPackageName());
            mContext.registerReceiver(mBroadcastReceiver, filter);
        } catch (Exception e) {

        }
    }

    protected void unregisterReceiver() {
        try {
            mContext.unregisterReceiver(mBroadcastReceiver);
        } catch (Exception e) {

        }
    }

    public static final Map<String, Integer> KEYCODE_MAP = new HashMap<String, Integer>();

    static {
        KEYCODE_MAP.put(WindowService.MSG_VIRTUAL_KEY_BACK, KeyEvent.KEYCODE_BACK);
        KEYCODE_MAP.put(WindowService.MSG_VIRTUAL_KEY_CENTER, KeyEvent.KEYCODE_DPAD_CENTER);
        KEYCODE_MAP.put(WindowService.MSG_VIRTUAL_KEY_LEFT, KeyEvent.KEYCODE_DPAD_LEFT);
        KEYCODE_MAP.put(WindowService.MSG_VIRTUAL_KEY_RIGHT, KeyEvent.KEYCODE_DPAD_RIGHT);
        KEYCODE_MAP.put(WindowService.MSG_VIRTUAL_KEY_UP, KeyEvent.KEYCODE_DPAD_UP);
        KEYCODE_MAP.put(WindowService.MSG_VIRTUAL_KEY_DOWN, KeyEvent.KEYCODE_DPAD_DOWN);
        KEYCODE_MAP.put(WindowService.MSG_VIRTUAL_KEY_HOME, KeyEvent.KEYCODE_HOME);
        KEYCODE_MAP.put(WindowService.MSG_VIRTUAL_KEY_MENU, KeyEvent.KEYCODE_MENU);
    }

    protected void back2Home() {
        mContext.startActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME));
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WindowService.PROTOCAL_CUSTOMER_DATA.equals(action)) {
                final String what = intent.getStringExtra("data");
                if ("key:home".equals(what)) {
                    back2Home();
                } else if ("key:menu".equals(what)) {
                    handleKey(KeyEvent.KEYCODE_MENU);
                }
                return;
            }
            try {
                handleKey(KEYCODE_MAP.get(action));
            } catch (Exception e) {
            }
        }
    };

    protected boolean requestNextFocus(int direction) {
        try {
            return mRootView.findFocus().focusSearch(direction).requestFocus();
        } catch (Exception e) {
        }
        return false;
    }

    @SuppressLint("NewApi")
    protected void handleKey(final int keyCode) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN
                || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_UP:
                if (requestNextFocus(View.FOCUS_UP)) {
                    return;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                if (requestNextFocus(View.FOCUS_DOWN)) {
                    return;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (requestNextFocus(View.FOCUS_LEFT)) {
                    return;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if (requestNextFocus(View.FOCUS_RIGHT)) {
                    return;
                }
                break;
            }
        }
        final long downTime = SystemClock.uptimeMillis();
        if (mDialog != null) {
            mDialog.dispatchKeyEvent(new KeyEvent(downTime, downTime, KeyEvent.ACTION_DOWN, keyCode, 0));
            mDialog.dispatchKeyEvent(new KeyEvent(downTime, SystemClock.uptimeMillis(), KeyEvent.ACTION_UP, keyCode, 0));
        } else if (mContext instanceof Activity) {
            ((Activity) mContext).dispatchKeyEvent(new KeyEvent(downTime, downTime, KeyEvent.ACTION_DOWN, keyCode, 0));
            ((Activity) mContext).dispatchKeyEvent(new KeyEvent(downTime, SystemClock.uptimeMillis(),
                    KeyEvent.ACTION_UP, keyCode, 0));
        }
    }

}
